package com.dexilaonian.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dexilaonian.R;
import com.dexilaonian.adpter.YiyangAdapter;
import com.dexilaonian.bean.ConfirmBean;
import com.dexilaonian.bean.DocBean;
import com.dexilaonian.bean.YiyangtBean;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Logutil;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.view.DividerItemDecoration;
import com.dexilaonian.widget.DateTimePickDialogUtil;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bakerj.backgrounddarkpopupwindow.BackgroundDarkPopupWindow;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ConfirmOrderActivity
        extends BaseActivity
        implements View.OnClickListener {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.iv_confirm)
    ImageView ivConfirm;
    @Bind(R.id.house_confirm_text)
    RelativeLayout houseConfirmText;
    @Bind(R.id.et_house_name)
    TextView etHouseName;
    @Bind(R.id.et_house_address)
    TextView etHouseAddress;
    @Bind(R.id.tv_change_person)
    TextView tvChangePerson;
    @Bind(R.id.tv_kangfuyishi)
    TextView tvKangfuyishi;
    @Bind(R.id.rl_choose_doctor)
    RelativeLayout rlChooseDoctor;
    @Bind(R.id.door_service_time)
    TextView doorServiceTime;
    @Bind(R.id.rl_door_service_time)
    RelativeLayout rlDoorServiceTime;
    @Bind(R.id.jian)
    ImageView jian;
    @Bind(R.id.tv_shuliang)
    TextView tvShuliang;
    @Bind(R.id.jia)
    ImageView jia;
    @Bind(R.id.tv_service_time)
    TextView tvServiceTime;
    @Bind(R.id.btn_ensure_order)
    TextView btnEnsureOrder;
    @Bind(R.id.tv_conentMethod)
    TextView mTvConentMethod;
    @Bind(R.id.tv_conentMethod_detail)
    TextView mTvConentMethodDetail;
    @Bind(R.id.tv_total)
    TextView tvTotal;
    @Bind(R.id.rllll)
    RelativeLayout rllll;
    @Bind(R.id.base_title_service)
    TextView baseTitleService;
    private ListView listview_dotor;
    private String confirm_url = Constant.base_url + "/customer/list.do";
    private int num = 1;
    private int mPrice;
    private String doc_url = Constant.base_url + "/serviceuser/getServiceUsersOfProject";
    private int mServiceuserid;
    private List<DocBean> mDoc_list;
    private RecyclerView recyclerView;
    private YiyangAdapter yiyangAdapter;
    private List<YiyangtBean> list = new ArrayList<>();
    private ArrayList<YiyangtBean> yiyangtBeen;
    private BackgroundDarkPopupWindow window;
    private int customer_id;
    private String address;
    private String realName;
    private String province;
    private String city;
    private String tel;
    private int gender;
    private String mNotice;
    private String mContent_time;
    private String mContent_method;
    private ArrayList<ConfirmBean> confirmBeen;
    private Bundle extras;
    private int positon = 0;
    private String projectid;
    private String serviceuserid;
    private String cardid;
    private String orderid;
    private TextView totalMoney;
    private String time;
    private String format;
    private int pay_money;
    private IWXAPI wxapi;

    @Override
    public int getLayoutID() {
        return R.layout.activity_confirm_order;
    }

    @Override
    public void initView() {

    }

    private void initGetconfirm() {
        Map map = new HashMap();
        Okhttp.postString(true, confirm_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
            }
            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(ConfirmOrderActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 0) {
                        String data = object.optString("data");
                        confirmBeen = JsonUtil.json2beans(data, ConfirmBean.class);
                        for (int i = 0; i < confirmBeen.size(); i++) {
                            customer_id = confirmBeen.get(i).getCustomer_id();
                            projectid = extras.getString("projectid");
                            serviceuserid = extras.getString("serviceuserid");
                            address = confirmBeen.get(i).getAddress();
                            realName = confirmBeen.get(i).getRealName();
                            province = confirmBeen.get(i)
                                    .getProvince();
                            city = confirmBeen.get(i)
                                    .getCity();
                            tel = confirmBeen.get(i)
                                    .getTel();
                            gender = confirmBeen.get(i)
                                    .getGender();
                            etHouseName.setText(realName);
                            etHouseAddress.setText(province + city + address);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        baseTitleService.setText("确认订单");
        wxapi = WXAPIFactory.createWXAPI(ConfirmOrderActivity.this, Constant.APP_ID, false);
        wxapi.registerApp(Constant.APP_ID);
        Intent intent = getIntent();
        extras = intent.getExtras();
        String confirm2 = extras.getString("CONFIRM2");
        if (!TextUtils.isEmpty(confirm2)) {
            String realAddress = extras.getString("realAddress");
            String realName1 = extras.getString("realName");
            projectid = extras.getString("projectid");
            serviceuserid = extras.getString("serviceuserid");
            customer_id = extras.getInt("customer_id");

            etHouseName.setText(realName1);
            etHouseAddress.setText(realAddress);
        } else {
            initGetconfirm();
        }
        mPrice = extras.getInt("PRICE");
        mNotice = extras.getString("mNotice");
        mContent_time = extras.getString("mContent_time");
        mContent_method = extras.getString("mContent_method");

        jian.setOnClickListener(this);
        jia.setOnClickListener(this);
        tvShuliang.setText(num + "");
        pay_money = num * mPrice;
        tvTotal.setText("￥" + pay_money);
        if (!TextUtils.isEmpty(mContent_method)) {
            mTvConentMethod.setText(mContent_method);
        }
        if (!TextUtils.isEmpty(mNotice)) {
            mTvConentMethodDetail.setText(mNotice);
        }
        if (!TextUtils.isEmpty(mContent_time)) {
            tvServiceTime.setText(mContent_time + "分钟");
        }
    }
    @OnClick({R.id.btn_ensure_order,
            R.id.back,
            R.id.house_confirm_text,
            R.id.tv_change_person,
            R.id.rl_choose_doctor,
            R.id.rl_door_service_time,
            R.id.jian,
            R.id.jia})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_change_person:
                Intent intent = new Intent(ConfirmOrderActivity.this, ServiceActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("PRICE", mPrice);
                intent.putExtras(bundle);
                intent.putExtra("mContent_time", mContent_time);
                intent.putExtra("serviceuserid", serviceuserid);
                intent.putExtra("mContent_method", mContent_method);
                intent.putExtra("mNotice", mNotice);
                intent.putExtra("projectid", projectid);
                intent.putExtra("CONFIRM", "CONFIRM");
                intent.putExtra("CONFIRM00", "");
                startActivity(intent);
                finish();
                break;
            case R.id.rl_choose_doctor:
                init();
                break;
            case R.id.rl_door_service_time:
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        ConfirmOrderActivity.this, time);
                dateTimePicKDialog.onCreateDialog(new DateTimePickDialogUtil.SelectDateTimeCallBack() {
                    @Override
                    public void isConfirm(String edString) {
                        SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        format = sfd.format(new Date(Long.parseLong(String.valueOf(edString))));
                        doorServiceTime.setText(format);
                    }
                });
                break;
            case R.id.jian:
                num--;
                if (num < 1) {
                    showToast("购买数量不能少于1");
                    return;
                }
                tvShuliang.setText(num + "");
                tvTotal.setText("￥" + num * mPrice);
                break;
            case R.id.jia:
                num++;
                tvShuliang.setText(num + "");
                tvTotal.setText("￥" + num * mPrice);
                break;
            case R.id.btn_ensure_order:
                String serviceTime = doorServiceTime.getText().toString().trim();
                String kangfuyishi = tvKangfuyishi.getText().toString().trim();
             /*   if (TextUtils.isEmpty(kangfuyishi)||kangfuyishi.equals("")) {
                    showToast("请选择服务人员");
                    return;
                }
                if (TextUtils.isEmpty(serviceTime)) {
                    showToast("请选择上门时间");
                    return;
                }*/
                showToast("服务暂时未开通...");
                 //initGetPay();
                break;
        }
    }

    private void initGetPay() {
        showProgressBar(true);
        Map<String, String> map = new HashMap<>();
        map.put("projectid", projectid + "");
        map.put("serviceuserid", serviceuserid);
        map.put("customerid", customer_id + "");
        map.put("quantity", num + "");
        map.put("time", format);
        String save_order_url = Constant.base_url + "/service/saveOrder.do";
        Okhttp.postString(true, save_order_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }
            @Override
            public void onResponse(String response, int id) {

                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(ConfirmOrderActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 0) {
                        String data = jsonObject.optString("data");
                        JSONObject object = new JSONObject(data);
                        orderid = object.optString("orderid");
                        String card = object.optString("card");
                        if ("null".equals(card)) {
                            showToast("请先申请孝心卡");
                            return;
                        }
                        JSONObject jsonObject2 = new JSONObject(card);
                        cardid = jsonObject2.optString("id");
                        String total_deposit = jsonObject2.optString("total_deposits");
                        showPopwindow_pay(total_deposit, pay_money);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
                showToast(state);
            }
        });
    }

    /**
     * 显示popupWindow
     */
    private void showPopwindow_pay(String total_deposit, int pay_money2) {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.popwindowlayout_pay, null);
        RelativeLayout deshengka = (RelativeLayout) view.findViewById(R.id.rl_deshengka);
        RelativeLayout alipay = (RelativeLayout) view.findViewById(R.id.rl_alipay);
        RelativeLayout wechat = (RelativeLayout) view.findViewById(R.id.rl_wechat);
        final ImageView ivka = (ImageView) view.findViewById(R.id.ivka1);
        final ImageView ivAlipay = (ImageView) view.findViewById(R.id.iv_alipay2);
        final ImageView ivWechat = (ImageView) view.findViewById(R.id.iv_wechat3);
        final TextView payMoney = (TextView) view.findViewById(R.id.tv_pay);
        final TextView balance_pay = (TextView) view.findViewById(R.id.tv_balance_pay);
        totalMoney = (TextView) view.findViewById(R.id.total_money);
        balance_pay.setText("（余额：￥" + total_deposit + "）");
        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
        totalMoney.setText("￥" + num * mPrice);
        window = new BackgroundDarkPopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                1100);
        window.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        window.setDarkStyle(-1);
        window.resetDarkPosition();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);
        window.setBackgroundDrawable(getResources().getDrawable(R.color.colorpopuwindow));
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(ConfirmOrderActivity.this.findViewById(R.id.rllll),
                Gravity.BOTTOM, 0, 0);
        deshengka.setOnClickListener(this);
        alipay.setOnClickListener(this);
        wechat.setOnClickListener(this);
        deshengka.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivka.setVisibility(View.VISIBLE);
                ivAlipay.setVisibility(View.GONE);
                ivWechat.setVisibility(View.GONE);
                positon = 0;
            }
        });
        alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivAlipay.setVisibility(View.VISIBLE);
                ivka.setVisibility(View.GONE);
                ivWechat.setVisibility(View.GONE);
                positon = 1;
            }
        });
        wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivWechat.setVisibility(View.VISIBLE);
                ivka.setVisibility(View.GONE);
                ivAlipay.setVisibility(View.GONE);
                positon = 2;
            }
        });
        payMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (positon == 0) {
                    if (!TextUtils.isEmpty(orderid) && !TextUtils.isEmpty(cardid)) {
                        desungroupPay(orderid, cardid);
                    } else {
                        showToast("未获取到支付订单");
                    }
                } else if (positon == 1) {
                    showToast("支付宝支付功能暂时未开通");
                    positon = 0;
                } else {
                    showToast("微信支付功能暂时未开通");
                    positon = 0;
                }
                window.dismiss();
            }
        });
        //popWindow消失监听方法
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }
    private void desungroupPay(String orderid, String cardid) {
        showProgressBar(true);
        String pay_url = Constant.base_url + "/service/payByVIPCard.do";
        Map<String, String> map = new HashMap<>();
        map.put("orderid", orderid);
        map.put("cardid", cardid);
        Okhttp.postString(true, pay_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(ConfirmOrderActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 0) {
                        showToast("支付成功");
                        window.dismiss();

                        Intent intent = new Intent(ConfirmOrderActivity.this, SuccessActivity.class);
                        String real_name = etHouseName.getText().toString().trim();
                        String HouseAddress = etHouseAddress.getText().toString().trim();
                        String money = totalMoney.getText().toString().trim();
                        intent.putExtra("real_name", real_name);
                        intent.putExtra("HouseAddress", HouseAddress);
                        intent.putExtra("money", money);
                        startActivity(intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
            }
        });

    }

    /**
     * 显示popupWindow
     */
    private void doctor_poWindow() {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context
                .LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_yiyang, null);
        window = new BackgroundDarkPopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                1100);
        recyclerView = (RecyclerView) view.findViewById(R.id.item_recyclerview);
        yiyangAdapter = new YiyangAdapter(ConfirmOrderActivity.this, list);
        recyclerView.setAdapter(yiyangAdapter);
        yiyangAdapter.setItemClickListener(new YiyangAdapter.MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String myname = yiyangtBeen.get(position).getName();
                tvKangfuyishi.setText(myname);
                window.dismiss();
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(ConfirmOrderActivity.this));
        //添加分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(ConfirmOrderActivity.this, DividerItemDecoration.VERTICAL_LIST));
        /*ImageView quxiao = (ImageView) view.findViewById(R.id.quxiao_confirm);
        DocAdapter adapter = new DocAdapter(ConfirmOrderActivity.this, mDoc_list);
        listview_dotor.setAdapter(adapter);
*/
        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()

        window.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        window.setDarkStyle(-1);
        window.resetDarkPosition();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);
        window.setBackgroundDrawable(getResources().getDrawable(R.color.colorpopuwindow));
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(ConfirmOrderActivity.this.findViewById(R.id.et_house_name),
                Gravity.BOTTOM, 0, 0);
    /*    quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
            }
        });*/
        //  window.showAsDropDown(nextNew, Gravity.BOTTOM, 0, 0);


        //popWindow消失监听方法
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }

    private void init() {
        showProgressBar(true);
        String yiyang_url = Constant.base_url + "/serviceuser/getServiceUserOfCompanyCategory";
        Map<String, String> map = new HashMap<>();
        map.put("city", "深圳市");
        map.put("category", "上门康养");
        map.put("index", "1");
        map.put("pageSize", "12");
        Okhttp.postString(false, yiyang_url, map, new Okhttp.CallBac() {

            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(ConfirmOrderActivity.this, LoginActivity.class));
                        return;
                    }
                    String data = jsonObject.optString("data");
                    JSONObject object = new JSONObject(data);
                    String items = object.optString("items");
                    Logutil.e("TTTitems=="+items);
                    if (items.equals("[]")) {
                        showToast("暂无医师数据");
                        return;
                    }
                    yiyangtBeen = JsonUtil.json2beans(items, YiyangtBean.class);
                    serviceuserid = String.valueOf(yiyangtBeen.get(positon).getId());
                    list.clear();
                    list.addAll(yiyangtBeen);

                    doctor_poWindow();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {

            }
        });
    }
}
